package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/orderSetting")
public class OrderSettingController {

    @Reference
    OrderSettingService orderSettingService;

    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile){
        try {
            List<String[]> stringsList = POIUtils.readExcel(excelFile);
            //把string数组转换成orderSetting对象
            List<OrderSetting> orderSettingList = new ArrayList<>();
            //循环
            for (String[] strs : stringsList) {
                //一个数组对应一个OrderSetting
                OrderSetting orderSetting  = new OrderSetting();
                //把字符串日期转换为日期类型
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                Date date = sdf.parse(strs[0]);
                //预约日期
                orderSetting.setOrderDate(date);
                //可预约人数
                orderSetting.setNumber(Integer.parseInt(strs[1]));
                //添加到集合中
                orderSettingList.add(orderSetting);
            }
            //发出请求，把orderSettingList写入数据库
            orderSettingService.addOrderSettings(orderSettingList);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }
}
